import axios from 'axios'
import qs from 'qs'
import router from '@/router'
import { ElMessage } from 'element-plus'

axios.defaults.baseURL = ''
axios.defaults.timeout = import.meta.env.VITE_TIMEOUT
axios.defaults.headers.post['Content-Type'] = 'application/json'

// ------------------- 请求拦截器 -------------------
axios.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token')
        if (token) {
            config.headers[import.meta.env.VITE_TOKEN_NAME] = import.meta.env.VITE_TOKEN_PREFIX + token
        }
        return config
    },
    (error) => Promise.reject(error)
)

// ------------------- 响应拦截器 -------------------
axios.interceptors.response.use(
    (response) => {
        const { request } = response || {}
        const { status, responseType } = request || {}
        if (responseType === 'blob') return response
        const { code, msg } = response.data
        if (status !== 200) return Promise.reject({ code, message, response })
        return response
    },
    (error) => {
        const res = error.response
        if (!res) {
            // 网络错误 / 超时
            ElMessage('网络异常，请稍后再试')
            return Promise.reject(error)
        }
        const { status, data } = res
        const { code, message } = data || {}

        // 统一处理 401
        if (status === 401) {
            const { code, message } = data || {}
            if (message) ElMessage(message)
            // 表示token过期或无效，跳转到登录页面
            if (code === 2002) {
                router.replace({
                    path: '/login',
                    query: {
                        t: Date.now(),
                        redirect: router.currentRoute.value.fullPath
                    }
                })
            }
        }
        return Promise.reject(error)
    }
)

const http = {

    /** get 请求
     * @param  url
     * @param  params
     * @param  config
     */
    get (url, params = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get', url, params, ...config
            }).then((response) => {
                const { code, message } = response.data
                resolve(response.data)
            }).catch((error) => {
                reject(error)
            })
        })
    },

    /** post 请求
     * @param  {string} url
     * @param  {请求参数} data
     * @param  {参数} config
     */
    post (url, data = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'post', url, data, ...config
            }).then((response) => {
                const { code, message } = response.data
                resolve(response.data)
            }).catch((error) => {
                reject(error)
            })
        })
    },

    /** get 请求 blob二进制流数据
     * @param  {接口地址} url
     * @param  {请求参数} data
     * @param  {参数} config
     */
    blob (url, params = {}, config = {}) {
        return new Promise((resolve, reject) => {
            axios({
                method: 'get', url, params, responseType: 'blob', ...config
            }).then((response) => {
                resolve(response.data)
            })
        })
    }

    // /** jsonp 请求
    //  * @param  {接口地址} url
    //  * @param  {JSONP回调函数名称} name
    //  */
    // jsonp: function (url, name = 'jsonp') {
    //     return new Promise((resolve) => {
    //         var script = document.createElement('script')
    //         var _id = `jsonp${Math.ceil(Math.random() * 1000000)}`
    //         script.id = _id
    //         script.type = 'text/javascript'
    //         script.src = url
    //         window[name] = (response) => {
    //             resolve(response)
    //             document.getElementsByTagName('head')[0].removeChild(script)
    //             try {
    //                 delete window[name];
    //             } catch (e) {
    //                 window[name] = undefined;
    //             }
    //         }
    //         document.getElementsByTagName('head')[0].appendChild(script)
    //     })
    // }
}

export default http
